<template>
  <div class="doctor-edit-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="title">医生信息</span>
        </div>
      </template>

      <el-form :model="doctorForm" label-width="120px" label-position="left">
        <!-- 医生编号 -->
        <el-form-item label="医生编号" prop="id">
          <el-input disabled v-model="doctorForm.id" />
        </el-form-item>

        <!-- 医生昵称 -->
        <el-form-item label="医生昵称" prop="username">
          <el-input v-model="doctorForm.username" placeholder="请输入医生昵称" />
        </el-form-item>

        <!-- 医生头像 -->
        <el-form-item label="医生头像">
          <div class="avatar-uploader">
            <el-avatar :size="100" :src="doctorForm.doctorAvatar" />
            <el-button type="primary" class="upload-btn" @click="dialogVisible = true">
              上传头像
            </el-button>
          </div>
        </el-form-item>

        <!-- 医生姓名 -->
        <el-form-item label="医生姓名" prop="doctorName">
          <el-input v-model="doctorForm.doctorName" placeholder="请输入医生真实姓名" />
        </el-form-item>

        <!-- 医生电话 -->
        <el-form-item label="医生电话" prop="phone">
          <el-input v-model="doctorForm.phone" placeholder="请输入医生电话" />
        </el-form-item>

        <!-- 医生角色 -->
        <el-form-item label="医生角色" prop="doctorRoleId">
          <el-select v-model="doctorForm.doctorRoleId" placeholder="请选择医生角色">
            <el-option
                v-for="item in roleOptions"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
            />
          </el-select>
        </el-form-item>

        <!-- 性别 -->
        <el-form-item label="性别" prop="gender">
          <el-select v-model="doctorForm.gender" placeholder="请选择性别">
            <el-option label="男" value="male" />
            <el-option label="女" value="female" />
          </el-select>
        </el-form-item>

        <!-- 医生介绍 -->
        <el-form-item label="医生介绍" prop="doctorIntro">
          <el-input
              v-model="doctorForm.doctorIntro"
              type="textarea"
              :rows="4"
              placeholder="请输入医生介绍"
          />
        </el-form-item>

        <!-- 医生擅长 -->
        <el-form-item label="医生擅长" prop="doctorExpertise">
          <el-input
              v-model="doctorForm.doctorExpertise"
              type="textarea"
              :rows="4"
              placeholder="请输入医生擅长领域"
          />
        </el-form-item>
      </el-form>

      <div class="footer-btns">
        <el-button type="primary" @click="handleSave">保存</el-button>
        <el-button @click="handleCancel">退出</el-button>
      </div>
    </el-card>

    <!-- 头像上传弹窗 -->
    <el-dialog v-model="dialogVisible" title="上传头像" width="30%">
      <el-upload
          class="avatar-uploader"
          :http-request="handleUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
      >
        <img v-if="doctorForm.doctorAvatar" :src="doctorForm.doctorAvatar" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
      <el-button type="warning" style="margin-top: 10px">点击上方即可上传</el-button>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="dialogVisible = false">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import router from "@/components/router/index.js";
import axios from "axios";
// pinia使用
import { userStore } from '/src/components/store/index.js'
const userItemStore = userStore();

import request from '/src/utils/request';

// 使用reactive定义表单数据，避免.value层级
const doctorForm = reactive({
  id: null,
  username: '',
  doctorAvatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
  doctorName: '',
  gender: 'male',
  doctorRoleId: null,
  doctorIntro: '',
  doctorExpertise: '',
  phone: '',
  role: { id: null, roleName: '' }
})

// 获取医生信息
const findUserById = () => {
  // 检查 user 是否存在
  if (!userItemStore.user) {
    ElMessage.error('用户数据未初始化');
    return;
  }

  request.get(`/personalProfile/findUserById/${userItemStore.user.id}`).then((resp) => {
    // 使用Object.assign合并数据，保持响应式
    Object.assign(doctorForm, resp.data);
  }).catch((error) => {
    ElMessage.error('获取医生信息失败，请稍后重试');
  })
}

// 获取角色选项
const roleOptions = ref([])
const getRoleOptions = () => {
  request.get(`/role/getRoleOptions`).then(resp => {
    roleOptions.value = resp.data
  }).catch(error => {
    console.error('获取角色选项失败:', error);
    ElMessage.error('获取角色列表失败，请稍后重试');
  })
}

// 头像上传相关
// 在 axios 配置中设置 baseURL
const instance = axios.create({
  baseURL: 'http://localhost:8081', // 指向你的后端地址
  timeout: 10000,
});

// 修改handleUpload方法
const handleUpload = async (options) => {
  const { file } = options;
  console.log('准备上传文件:', file.name, file.size);

  const formData = new FormData();
  formData.append('file', file);

  try {
    const response = await instance.post('/api/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });

    console.log('上传响应:', response.data);

    if (response.data && (response.data.code === 200 || response.status === 200)) {
      return response.data;
    }
    throw new Error(response.data?.message || '上传失败');
  } catch (error) {
    console.error('上传出错:', error);
    let errorMsg = error.response?.data?.message ||
        error.message ||
        '上传失败，请检查网络连接';
    ElMessage.error(errorMsg);
    throw error;
  }
};

const handleAvatarSuccess = (response, uploadFile) => {
  console.log('上传成功回调:', response);

  // 兼容不同响应格式
  const successCode = [200, '200'];
  if (successCode.includes(response?.code) || successCode.includes(response?.status)) {
    const imageUrl = response.data || response.url;
    if (imageUrl) {
      doctorForm.doctorAvatar = imageUrl;
      ElMessage.success(response.message || '上传成功');
      userItemStore.user.doctorAvatar = imageUrl;
    } else {
      ElMessage.error('未获取到有效图片URL');
    }
  } else {
    ElMessage.error(response?.message || '上传失败');
  }
};

const dialogVisible = ref(false)

const beforeAvatarUpload = (file) => {
  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPGOrPNG) {
    ElMessage.error('头像图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!')
  }
  return isJPGOrPNG && isLt2M
}

// 保存按钮事件
const handleSave = () => {
  // 表单验证
  // 这里可以添加额外的前端验证逻辑

  request.put(`/personalProfile/editUser`, doctorForm).then((resp) => {
    ElMessage.success(resp.data || '保存成功');
    router.push("/main")
  }).catch(error => {
    console.error('保存失败:', error);
    ElMessage.error(error.response?.data?.message || '保存失败，请稍后重试');
  })
}

// 退出按钮事件
const handleCancel = () => {
  router.push("/main")
}

// 初始化数据
onMounted(() => {
  findUserById();
  getRoleOptions();
})
</script>

<style scoped>
.doctor-edit-container {
  padding: 20px;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.avatar-uploader {
  display: flex;
  align-items: center;
  gap: 20px;
}

.upload-btn {
  margin-left: 20px;
}

.footer-btns {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  gap: 20px;
}

/* 头像上传样式 */
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}
</style>